package com.demo.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author gy
 * @date 2022/5/14
 * 利用 buffer 既可以读，又可以写
 * 一次性完成对文件的拷贝
 */
public class NIOFileChannel03 {
    public static void main(String[] args) throws Exception{

        FileInputStream fileInputStream = new FileInputStream("20220514-netty-study/src/main/resources/1.txt");
        FileChannel fileChannel01 = fileInputStream.getChannel();

        FileOutputStream fileOutputStream = new FileOutputStream("20220514-netty-study/src/main/resources/2.txt");
        FileChannel fileChannel02 = fileOutputStream.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(5);

        // 循环读取文件
        while (true) {
            /*
            这里有一个重要的操作，一定不要忘了
            position = 0;
            limit = capacity;
            mark = -1;
            return this;
            重要是重置 position的值
             */
            byteBuffer.clear();

            int read = fileChannel01.read(byteBuffer);
            System.out.println("read = "+read);
            // 表示读完
            if (read == -1){
                break;
            }
            // 将 buffer 中的数据写入到 fileChannel02 -》 2.txt
            // buffer 进行读写切换 读 -> 写
            byteBuffer.flip();
            fileChannel02.write(byteBuffer);
        }
    }
}
